package com.jyxd.web.controller.patient;

import com.jyxd.web.config.TenantEnum;
import com.jyxd.web.data.basic.CommonSetting;
import com.jyxd.web.data.dto.HttpResult;
import com.jyxd.web.data.patient.Patient;
import com.jyxd.web.data.patient.PatientCureEvent;
import com.jyxd.web.data.patient.PatientTransferInfo;
import com.jyxd.web.data.user.User;
import com.jyxd.web.mq.HisViewProduction;
import com.jyxd.web.service.assessment.basic.CommonSettingService;
import com.jyxd.web.service.hisview.dto.HisViewDataDto;
import com.jyxd.web.service.patient.IPatientCureEventService;
import com.jyxd.web.service.patient.IPatientTransferInfoService;
import com.jyxd.web.service.patient.PatientMiddleService;
import com.jyxd.web.service.patient.PatientService;
import com.jyxd.web.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.*;

import static com.jyxd.web.config.ConstantConfig.HIS_VIEW_EVENT_DC_HLCZJL_BZBWHL_ZDXX;
import static com.jyxd.web.config.ConstantConfig.HIS_VIEW_EVENT_DC_ICU_DAT_BRXXJLK;
import static com.jyxd.web.util.UUIDUtil.getUUID;

@Api(tags = "患者信息相关接口")
@Controller
@RequestMapping(value = "/patient")
public class PatientController {

    private static Logger logger = LoggerFactory.getLogger(PatientController.class);

    @Autowired
    private PatientService patientService;

    @Autowired
    private CommonSettingService commonSettingService;

    @Autowired
    private HisViewProduction hisViewProduction;
    @Autowired
    private PatientMiddleService patientMiddleService;
    @Autowired
    private IPatientTransferInfoService patientTransferInfoService;
    @Autowired
    private IPatientCureEventService patientCureEventService;

    /**
     * 增加一条病人表记录
     *
     * @return
     */
    @RequestMapping(value = "/insert")
    @ResponseBody
    public String insert(@RequestBody Patient patient) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "系统开小差了，请稍后再试。");
        patient.setId(getUUID());
        patient.setCreateTime(new Date());
        patientService.insert(patient, false);
        json.put("code", HttpCode.OK_CODE.getCode());
        json.put("msg", "添加成功");
        return json.toString();
    }

    /**
     * 更新病人表记录状态
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public String update(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "系统开小差了，请稍后再试。");
        if (map != null && map.containsKey("id") && map.containsKey("status")) {
            Patient patient = patientService.queryData(map.get("id").toString());
            if (patient != null) {
                patient.setStatus(Integer.valueOf(map.get("status").toString()));
                patientService.update(patient);
                json.put("msg", "更新成功");
            } else {
                json.put("msg", "更新失败，没有这个对象。");
                return json.toString();
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 更新病人出科、出院等数据
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/updatePatient")
    @ResponseBody
    public String updatePatient(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "系统开小差了，请稍后再试。");
        try {
            if (map != null && map.containsKey("id")) {
                Patient patient = patientService.queryData(map.get("id").toString());
                if (patient != null) {
                    if (StringUtils.isNotEmpty((String) map.get("status"))) {
                        patient.setStatus((Integer) map.get("status"));
                    }
                    if (StringUtils.isNotEmpty((String) map.get("enterTime"))) {
                        patient.setEnterTime(DateUtil.yyyyMMddHHmmssSdfToDate((String) map.get("enterTime")));
                    }
                    if (StringUtils.isNotEmpty((String) map.get("exitTime"))) {
                        patient.setExitTime(DateUtil.yyyyMMddHHmmssSdfToDate((String) map.get("exitTime")));
                    }
                    if (StringUtils.isNotEmpty((String) map.get("deathTime"))) {
                        patient.setDeathTime(DateUtil.yyyyMMddHHmmssSdfToDate((String) map.get("deathTime")));
                    }
                    if (StringUtils.isNotEmpty((String) map.get("flag"))) {
                        patient.setFlag(Integer.parseInt((String) map.get("flag")));
                    }
                    if (StringUtils.isNotEmpty((String) map.get("exitType"))) {
                        patient.setExitType((String) map.get("exitType"));
                    }
                    if (StringUtils.isNotEmpty((String) map.get("departmentCode"))) {
                        patient.setDepartmentCode((String) map.get("departmentCode"));
                    }
                    if (StringUtils.isNotEmpty((String) map.get("wardCode"))) {
                        patient.setWardCode((String) map.get("wardCode"));
                    }
                    if (StringUtils.isNotEmpty((String) map.get("toDepartmentCode"))) {
                        patient.setToDepartmentCode((String) map.get("toDepartmentCode"));
                    }
                    if (StringUtils.isNotEmpty((String) map.get("inDepartmentCode"))) {
                        patient.setInDepartmentCode((String) map.get("inDepartmentCode"));
                    }
                    if (StringUtils.isNotEmpty((String) map.get("bedCode"))) {
                        patient.setBedCode((String) map.get("bedCode"));
                    }
                    patientService.update(patient);
                    json.put("msg", "更新成功");
                } else {
                    json.put("msg", "更新失败，没有这个对象。");
                    return json.toString();
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 更新病人表记录状态
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/updateDiagnosisName")
    @ResponseBody
    public String updateDiagnosisName(@RequestBody(required = false) Map<String, Object> map,HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "系统开小差了，请稍后再试。");
        if (map != null && map.containsKey("id") && map.containsKey("diagnosisName")) {
            Patient patient = patientService.queryData(map.get("id").toString());
            if (patient != null) {
                patient.setDiagnosisName(map.get("diagnosisName").toString());
                patientService.update(patient);

                savePatientCureEvent(PatientEvent.DIAGNOSIS.getCode(),map.get("diagnosisName").toString(), patient,(User)session.getAttribute("user"));
                // 如果新增患者为重症科室患者时，新增数据中心患者诊断信息
                hisViewProduction.put(new HisViewDataDto(HIS_VIEW_EVENT_DC_HLCZJL_BZBWHL_ZDXX, patient));
                json.put("msg", "更新成功");
            } else {
                json.put("msg", "更新失败，没有这个对象。");
                return json.toString();
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    private void savePatientCureEvent(String eventCode,String name, Patient patient,User user) {
        PatientCureEvent event = new PatientCureEvent();
        event.setId(getUUID());
        event.setEventCode(eventCode);
        if(StringUtils.isNotEmpty(name)){
            event.setName(name);
        }
        event.setPatientId(patient.getId());
        event.setVisitCode(patient.getVisitCode());
        event.setVisitId(patient.getVisitId());
        event.setCreateTime(LocalDateTime.now());
        event.setDataSource(1);
        event.setEventDate(LocalDateTime.now());
        event.setUserId(user.getId());
        patientCureEventService.save(event);
    }

    /**
     * 更新病人非计划转入icu的状态
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/updatePatientIcuFlag")
    @ResponseBody
    public String updateICUFlag(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "系统开小差了，请稍后再试。");
        if (map != null && map.containsKey("id") && map.containsKey("icuFlag")) {
            Patient patient = patientService.queryData(map.get("id").toString());
            if (patient != null) {

                if (map.get("icuFlag") != null && !"".equals(map.get("icuFlag"))) {
                    patient.setUnplanned(Integer.parseInt(map.get("icuFlag").toString()));
                    patientService.update(patient);
                    // 如果新增患者为重症科室患者时，新增数据中心患者诊断信息
                    hisViewProduction.put(new HisViewDataDto(HIS_VIEW_EVENT_DC_ICU_DAT_BRXXJLK, patient));
                    json.put("data", patient);
                }
                json.put("msg", "更新成功");
            } else {
                json.put("msg", "更新失败，没有这个对象。");
                return json.toString();
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 编辑病人表
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
    public String edit(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "系统开小差了，请稍后再试。");
        if (map != null && map.containsKey("id") && map.containsKey("status") && map.containsKey("bedName")) {
            Patient patient = patientService.queryData(map.get("id").toString());
            if (patient != null) {
                patient.setStatus((int) map.get("status"));
                patientService.update(patient);
                json.put("msg", "编辑成功");
            } else {
                json.put("msg", "编辑失败，没有这个对象。");
                return json.toString();
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());

        return json.toString();
    }

    /**
     * 删除病人表记录
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public String delete(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "系统开小差了，请稍后再试。");
        if (map.containsKey("id")) {
            Patient patient = patientService.queryData(map.get("id").toString());
            if (patient != null) {
                patient.setStatus(-1);
                patientService.update(patient);
                json.put("msg", "删除成功");
            } else {
                json.put("msg", "删除失败，没有这个对象。");
                return json.toString();
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 根据主键id查询病人表记录
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/queryData", method = RequestMethod.POST)
    @ResponseBody
    public String queryData(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        if (map != null && map.containsKey("id")) {
            Patient patient = patientService.queryData(map.get("id").toString());
            if (patient != null) {
                json.put("msg", "查询成功");
                json.put("data", JSONObject.fromObject(patient));
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 根据条件分页查询病人表记录列表（也可以不分页）
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/queryList", method = RequestMethod.POST)
    @ResponseBody
    public String queryList(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        if (map != null && map.containsKey("start")) {
            int totalCount = patientService.queryNum(map);
            map.put("start", ((int) map.get("start") - 1) * (int) map.get("size"));
            json.put("totalCount", totalCount);
        }
        List<Patient> list = patientService.queryList(map);
        if (list != null && list.size() > 0) {
            json.put("msg", "查询成功");
            json.put("data", JSONArray.fromObject(list));
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 根据条件分页查询病人表记录列表（也可以不分页）
     *
     * @param map
     * @return
     */
    @ApiOperation("查询其他科室病人记录列表")
    @RequestMapping(value = "/queryOtherList", method = RequestMethod.POST)
    @ResponseBody
    public String queryOtherList(@RequestBody(required = false) Map<String, Object> map,HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");

        User user=(User)session.getAttribute("user");
        if(user!=null && StringUtils.isNotEmpty(user.getTenantId())){
            String tenantId = user.getTenantId();
            if(TenantEnum.ICU.getTenantId().equals(tenantId)){
                map.put("departmentCode",TenantEnum.ICU.getDepartmentName());
            } else if (TenantEnum.SHENNEI.getTenantId().equals(tenantId)) {
                map.put("departmentCode",TenantEnum.SHENNEI.getDepartmentName());
            }
        }

        if (map != null && map.containsKey("start")) {
            int totalCount = patientService.queryOtherNum(map);
            map.put("start", ((int) map.get("start") - 1) * (int) map.get("size"));
            json.put("totalCount", totalCount);
        }
        List<Patient> list = patientService.queryOtherList(map);
        if (list != null && list.size() > 0) {
            json.put("msg", "查询成功");
            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.registerJsonValueProcessor(Timestamp.class, new JsonArrayValueProcessor());
            json.put("data", JSONArray.fromObject(list, jsonConfig));
        }


        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 根据条件分页查询病人表记录列表（也可以不分页）--多表查询
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/getList", method = RequestMethod.POST)
    @ResponseBody
    public String getList(@RequestBody(required = false) Map<String, Object> map, HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");

        User user=(User)session.getAttribute("user");
        if(user!=null && StringUtils.isNotEmpty(user.getTenantId())){
            String tenantId = user.getTenantId();
            if(TenantEnum.ICU.getTenantId().equals(tenantId)){
                map.put("status",TenantEnum.ICU.getPatientStatus());
            } else if (TenantEnum.SHENNEI.getTenantId().equals(tenantId)) {
                map.put("status",TenantEnum.SHENNEI.getPatientStatus());
            }
        }

        if (map != null && map.containsKey("start")) {
            int totalCount = patientService.getNum(map);
            map.put("start", ((int) map.get("start") - 1) * (int) map.get("size"));
            json.put("totalCount", totalCount);
        }
        List<Map<String, Object>> list = patientService.getList(map);
        if (list != null && list.size() > 0) {
            json.put("msg", "查询成功");
            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.registerJsonValueProcessor(Timestamp.class, new JsonArrayValueProcessor());
            json.put("data", JSONArray.fromObject(list, jsonConfig));
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 查询所有病人数量
     *
     * @return
     */
    @RequestMapping(value = "/getAllNum", method = RequestMethod.POST)
    @ResponseBody
    public String getAllNum() {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        int num = patientService.getAllNum();
        json.put("num", num);
        json.put("msg", "查询成功");
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 导出病人信息excel
     *
     * @return
     */
    @RequestMapping(value = "/downloadPatient", method = RequestMethod.POST)
    @ResponseBody
    public void downloadPatient(@RequestBody(required = false) Map<String, Object> map, HttpServletResponse response) throws Exception {
        List<LinkedHashMap<String, Object>> list = patientService.getDownloadList(map);
        if (list != null && list.size() > 0) {
            ExportExcelUtil.exportExcel(response, "病人信息统计" + System.currentTimeMillis() + ".xlsx", setExcelData(list));
        }
    }

    /**
     * 〈设置表格数据〉<br>
     *
     * @param
     * @return ExcelData
     * @author
     * @update
     * @exception/throws [异常类型] [异常说明]
     * @see [类、类#方法、类#成员]
     * @since [起始版本]
     */
    public static ExcelData setExcelData(List<LinkedHashMap<String, Object>> list) {
        ExcelData data = new ExcelData();
        data.setName("病人信息统计表");
        List<String> titles = new ArrayList();
        titles.add("住院号");
        titles.add("姓名");
        titles.add("性别");
        titles.add("入科时间");
        titles.add("出科时间");
        titles.add("当前状态");
        titles.add("出科方式");
        titles.add("当前科室");
        titles.add("去向科室");
        titles.add("入科床号");
        titles.add("住院时间");
        titles.add("是否非计划");
        titles.add("病情");
        titles.add("责任医生");
        titles.add("责任护士");
        titles.add("最新手术时间");
        titles.add("最新手术名称");
        titles.add("诊断");
        titles.add("过敏史");
        titles.add("阳性");
        data.setTitles(titles);
        if (list != null && list.size() > 0) {
            List<List<Object>> rows = new ArrayList();
            for (int i = 0; i < list.size(); i++) {
                List<Object> row1 = new ArrayList();
                row1.add(list.get(i).get("住院号"));
                row1.add(list.get(i).get("姓名"));
                row1.add(list.get(i).get("性别"));
                row1.add(list.get(i).get("入科时间"));
                row1.add(list.get(i).get("出科时间"));
                row1.add(list.get(i).get("当前状态"));
                row1.add(list.get(i).get("出科方式"));
                row1.add(list.get(i).get("当前科室"));
                row1.add(list.get(i).get("去向科室"));
                row1.add(list.get(i).get("入科床号"));
                row1.add(list.get(i).get("住院时间"));
                row1.add(list.get(i).get("是否非计划"));
                row1.add(list.get(i).get("病情"));
                row1.add(list.get(i).get("责任医生"));
                row1.add(list.get(i).get("责任护士"));
                row1.add(list.get(i).get("最新手术时间"));
                row1.add(list.get(i).get("最新手术名称"));
                row1.add(list.get(i).get("诊断"));
                row1.add(list.get(i).get("过敏史"));
                row1.add(list.get(i).get("阳性"));

                rows.add(row1);
            }
            data.setRows(rows);
        }
        return data;
    }

    /**
     * 导出病人信息excel（暂时不用这个接口）
     *
     * @return
     */
    @RequestMapping(value = "/exportPatient", method = RequestMethod.GET)
    @ResponseBody
    public void exportPatient(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //String keyword = request.getParameter("keyword");
        patientService.getExcel(request, response);
        System.out.println("导出成功");
    }

    /**
     * 首页查询患者现有数量 今日转入数量 今日转出数量
     *
     * @return
     */
    @RequestMapping(value = "/getNowPatientNum", method = RequestMethod.POST)
    @ResponseBody
    public String getNowPatientNum(HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");

        User user=(User)session.getAttribute("user");

        Map<String, Object> map = new HashMap();
        if(user!=null && StringUtils.isNotEmpty(user.getTenantId())){
            String tenantId = user.getTenantId();
            if(TenantEnum.ICU.getTenantId().equals(tenantId)){
                map.put("status",TenantEnum.ICU.getPatientStatus());
            } else if (TenantEnum.SHENNEI.getTenantId().equals(tenantId)) {
                map.put("status",TenantEnum.SHENNEI.getPatientStatus());
            }
        }

        map.put("existing", "existing");//患者现有数量sql查询条件
        int existingNum = patientService.getNowPatientNum(map);
        map.clear();
        map.put("todayEnter", "todayEnter");//患者今日转入数量sql查询条件
        int todayEnterNum = patientService.getNowPatientNum(map);
        map.clear();
        map.put("todayExit", "todayExit");//患者今日转出数量sql查询条件
        int todayExitNum = patientService.getNowPatientNum(map);
        json.put("existingNum", existingNum);
        json.put("todayEnterNum", todayEnterNum);
        json.put("todayExitNum", todayExitNum);
        json.put("msg", "查询成功");
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 首页查询在科病人来源
     *
     * @return
     */
    @RequestMapping(value = "/getPatientSource", method = RequestMethod.POST)
    @ResponseBody
    public String getPatientSource(HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");

        User user=(User)session.getAttribute("user");

        Map<String, Object> map = new HashMap();
        if(user!=null && StringUtils.isNotEmpty(user.getTenantId())){
            String tenantId = user.getTenantId();
            if(TenantEnum.ICU.getTenantId().equals(tenantId)){
                map.put("status",TenantEnum.ICU.getPatientStatus());
            } else if (TenantEnum.SHENNEI.getTenantId().equals(tenantId)) {
                map.put("status",TenantEnum.SHENNEI.getPatientStatus());
            }
        }
        JSONArray array = patientService.getPatientSource(map);
        json.put("data", array);
        json.put("msg", "查询成功");
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 首页查询本月转入和转出
     *
     * @return
     */
    @RequestMapping(value = "/getMonthPatient", method = RequestMethod.POST)
    @ResponseBody
    public String getMonthPatient(HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        Map<String, Object> map = new HashMap();
        User user=(User)session.getAttribute("user");

        if(user!=null && StringUtils.isNotEmpty(user.getTenantId())){
            String tenantId = user.getTenantId();
            if(TenantEnum.ICU.getTenantId().equals(tenantId)){
                map.put("status",TenantEnum.ICU.getPatientStatus());
            } else if (TenantEnum.SHENNEI.getTenantId().equals(tenantId)) {
                map.put("status",TenantEnum.SHENNEI.getPatientStatus());
            }
        }
        map.put("monthEnter", "monthEnter");//患者本月转入数量sql查询条件
        int monthEnterNum = patientService.getNowPatientNum(map);
        map.remove("monthEnter");
        map.put("monthExit", "monthExit");//患者本月转出数量sql查询条件
        int monthExitNum = patientService.getNowPatientNum(map);
        JSONArray array = new JSONArray();
        JSONObject obj1 = new JSONObject();
        obj1.put("value", monthEnterNum);
        obj1.put("name", "转入");
        JSONObject obj2 = new JSONObject();
        obj2.put("value", monthExitNum);
        obj2.put("name", "转出");
        array.add(obj1);
        array.add(obj2);
        json.put("data", array);
        json.put("msg", "查询成功");
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 首页查询床位列表
     *
     * @return
     */
    @ApiOperation("查询患者在床患者")
    @RequestMapping(value = "/getBedPatientList", method = RequestMethod.POST)
    @ResponseBody
    public String getBedPatientList(HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");

        User user=(User)session.getAttribute("user");
        Map<String,Object> map = new HashMap<>();
        if(user!=null && StringUtils.isNotEmpty(user.getTenantId())){
            String tenantId = user.getTenantId();
            if(TenantEnum.ICU.getTenantId().equals(tenantId)){
                map.put("officeCode",TenantEnum.ICU.getOfficeCode());
                map.put("status",TenantEnum.ICU.getPatientStatus());
            } else if (TenantEnum.SHENNEI.getTenantId().equals(tenantId)) {
                map.put("officeCode",TenantEnum.SHENNEI.getOfficeCode());
                map.put("status",TenantEnum.SHENNEI.getPatientStatus());
            }
        }
        List<Map<String, Object>> list = patientService.getPatientDiagnosisName(map);
        if (list != null && list.size() > 0) {
            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.registerJsonValueProcessor(Timestamp.class, new JsonArrayValueProcessor());
            json.put("data", JSONArray.fromObject(list, jsonConfig));
            json.put("msg", "查询成功");
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 查询待分配的病人列表（是否分配床位）
     *
     * @return
     */
    @RequestMapping(value = "/getNoBedPatientList", method = RequestMethod.POST)
    @ResponseBody
    public String getNoBedPatientList(@RequestBody(required = false) Map<String, Object> map,HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");

        User user=(User)session.getAttribute("user");
        if(user!=null && StringUtils.isNotEmpty(user.getTenantId())){
            String tenantId = user.getTenantId();
            if(TenantEnum.ICU.getTenantId().equals(tenantId)){
                map.put("status",TenantEnum.ICU.getPatientStatus());
            } else if (TenantEnum.SHENNEI.getTenantId().equals(tenantId)) {
                map.put("status",TenantEnum.SHENNEI.getPatientStatus());
            }
        }
        List<Patient> list = patientService.getNoBedPatientList(map);
        if (list != null && list.size() > 0) {
            json.put("data", JSONArray.fromObject(list));
            json.put("msg", "查询成功");
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 查询已出科的病人列表
     *
     * @return
     */
    @RequestMapping(value = "/getOutPatientList", method = RequestMethod.POST)
    @ResponseBody
    public String getOutPatientList(@RequestBody(required = false) Map<String, Object> map,HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");

        User user=(User)session.getAttribute("user");
        if(user!=null && StringUtils.isNotEmpty(user.getTenantId())){
            String tenantId = user.getTenantId();
            if(TenantEnum.ICU.getTenantId().equals(tenantId)){
                map.put("status",TenantEnum.ICU.getPatientStatus());
            } else if (TenantEnum.SHENNEI.getTenantId().equals(tenantId)) {
                map.put("status",TenantEnum.SHENNEI.getPatientStatus());
            }
        }
        List<Patient> list = patientService.getOutPatientList(map);
        if (list != null && list.size() > 0) {
            json.put("data", JSONArray.fromObject(list));
            json.put("msg", "查询成功");
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 统计分析--出入科--转入转出分析
     *
     * @return
     */
    @RequestMapping(value = "/getOutAndIn", method = RequestMethod.POST)
    @ResponseBody
    public String getOutAndIn(@RequestBody(required = false) Map<String, Object> map, HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        JSONArray array = new JSONArray();
        JSONObject enterObj = new JSONObject();
        JSONObject exitObj = new JSONObject();
        enterObj.put("name", "转入患者");
        enterObj.put("value", 0);
        exitObj.put("name", "转出患者");
        exitObj.put("value", 0);

        User user=(User)session.getAttribute("user");
        if(user!=null && StringUtils.isNotEmpty(user.getTenantId())){
            String tenantId = user.getTenantId();
            if(TenantEnum.ICU.getTenantId().equals(tenantId)){
                map.put("status",TenantEnum.ICU.getPatientStatus());
            } else if (TenantEnum.SHENNEI.getTenantId().equals(tenantId)) {
                map.put("status",TenantEnum.SHENNEI.getPatientStatus());
            }
        }

        if (map.containsKey("type")) {
            //flag 0：出科  1：在科
            if (map.get("type").toString().equals("按天")) {
                String startTime = map.get("startTime").toString();
                String endTime = map.get("endTime").toString();
                map.put("flag", 0);//出科
                map.put("exitStartTime", startTime);
                map.put("exitEndTime", endTime);
                //int exitNum = patientService.getOutAndIn(map);
                //exitObj.put("value", exitNum);
                map.put("flag", 1);//在科
                map.put("enterStartTime", startTime);
                map.put("enterEndTime", endTime);
                //int enterNum = patientService.getOutAndIn(map);
                //enterObj.put("value", enterNum);
            }
            if (map.get("type").toString().equals("按月")) {
                String year = "";
                if (map.get("year") == null || "".equals(map.get("year"))) {
                    Calendar date = Calendar.getInstance();
                    year = String.valueOf(date.get(Calendar.YEAR));
                }
                String startTime = year + "-01-01";
                String endTime = year + "-12-31";
                map.put("flag", 0);//出科
                map.put("exitStartTime", startTime);
                map.put("exitEndTime", endTime);
                //int exitNum = patientService.getOutAndIn(map);
                //exitObj.put("value", exitNum);
                map.put("flag", 1);//在科
                map.put("enterStartTime", startTime);
                map.put("enterEndTime", endTime);
                //int enterNum = patientService.getOutAndIn(map);
                //enterObj.put("value", enterNum);
            }
            Map<String,Object> result = patientService.getOutAndInTotal(map);
            exitObj.put("value",result.get("exitNum"));
            enterObj.put("value",result.get("enterNum"));
        }

        array.add(exitObj);
        array.add(enterObj);
        json.put("data", array);
        json.put("msg", "查询成功");
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 统计分析--出入科--转出方式分析
     *
     * @return
     */
    @RequestMapping(value = "/getExitType", method = RequestMethod.POST)
    @ResponseBody
    public String getExitType(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        JSONArray array = new JSONArray();
        JSONObject obj1 = new JSONObject();
        JSONObject obj2 = new JSONObject();
        JSONObject obj3 = new JSONObject();
        JSONObject obj4 = new JSONObject();
        JSONObject obj5 = new JSONObject();
        obj1.put("name", "出院患者");
        obj1.put("value", 0);
        obj2.put("name", "转科患者");
        obj2.put("value", 0);
        obj3.put("name", "死亡患者");
        obj3.put("value", 0);
        obj4.put("name", "放弃患者");
        obj4.put("value", 0);
        obj5.put("name", "转院患者");
        obj5.put("value", 0);
        if (map.containsKey("type")) {
            //flag 0：出科  1：在科
            if (map.get("type").toString().equals("按天")) {
                String startTime = map.get("startTime").toString();
                String endTime = map.get("endTime").toString();
                map.put("flag", 0);//出科
                map.put("exitStartTime", startTime);
                map.put("exitEndTime", endTime);
                map.put("exitType", "出院");
                int num1 = patientService.getOutAndIn(map);
                obj1.put("value", num1);
                map.put("exitType", "转科");
                int num2 = patientService.getOutAndIn(map);
                obj2.put("value", num2);
                map.put("exitType", "死亡");
                int num3 = patientService.getOutAndIn(map);
                obj3.put("value", num3);
                map.put("exitType", "放弃");
                int num4 = patientService.getOutAndIn(map);
                obj4.put("value", num4);
                map.put("exitType", "转院");
                int num5 = patientService.getOutAndIn(map);
                obj5.put("value", num5);
            }
            if (map.get("type").toString().equals("按月")) {
                String year = "";
                if (map.get("year") == null || "".equals(map.get("year"))) {
                    Calendar date = Calendar.getInstance();
                    year = String.valueOf(date.get(Calendar.YEAR));
                }
                String startTime = year + "-01-01";
                String endTime = year + "-12-31";
                map.put("flag", 0);//出科
                map.put("exitStartTime", startTime);
                map.put("exitEndTime", endTime);
                map.put("exitType", "出院");
                int num1 = patientService.getOutAndIn(map);
                obj1.put("value", num1);
                map.put("exitType", "转科");
                int num2 = patientService.getOutAndIn(map);
                obj2.put("value", num2);
                map.put("exitType", "死亡");
                int num3 = patientService.getOutAndIn(map);
                obj3.put("value", num3);
                map.put("exitType", "放弃");
                int num4 = patientService.getOutAndIn(map);
                obj4.put("value", num4);
                map.put("exitType", "转院");
                int num5 = patientService.getOutAndIn(map);
                obj5.put("value", num5);
            }
        }
        array.add(obj1);
        array.add(obj2);
        array.add(obj3);
        array.add(obj4);
        array.add(obj5);
        json.put("data", array);
        json.put("msg", "查询成功");
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 统计分析--出入科--转入科室分析
     *
     * @return
     */
    @RequestMapping(value = "/getEnterDepartment", method = RequestMethod.POST)
    @ResponseBody
    public String getEnterDepartment(@RequestBody(required = false) Map<String, Object> map, HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");

        User user=(User)session.getAttribute("user");
        if(user!=null && StringUtils.isNotEmpty(user.getTenantId())){
            String tenantId = user.getTenantId();
            if(TenantEnum.ICU.getTenantId().equals(tenantId)){
                map.put("status",TenantEnum.ICU.getPatientStatus());
                map.put("department",TenantEnum.ICU.getDepartmentName());
            } else if (TenantEnum.SHENNEI.getTenantId().equals(tenantId)) {
                map.put("status",TenantEnum.SHENNEI.getPatientStatus());
                map.put("department",TenantEnum.SHENNEI.getDepartmentName());
            }
        }

        try {
            if (map.get("type").toString().equals("按天")) {
                String startTime = map.get("startTime").toString();
                String endTime = map.get("endTime").toString();
                map.put("enterStartTime", startTime);
                map.put("enterEndTime", endTime);
                map.put("flag", 1);// 在科
            }
            if (map.get("type").toString().equals("按月")) {
                String year = "";
                if (map.get("year") == null || "".equals(map.get("year"))) {
                    Calendar date = Calendar.getInstance();
                    year = String.valueOf(date.get(Calendar.YEAR));
                }
                String startTime = year + "-01-01";
                String endTime = year + "-12-31";
                map.put("enterStartTime", startTime);
                map.put("enterEndTime", endTime);
                map.put("flag", 1);// 在科
            }

            List<Map<String, Object>> list = patientMiddleService.getAllEnterDepartment(map);
            /*List<Map<String, Object>> list = patientService.getAllEnterDepartment(map);
            JSONArray array = new JSONArray();
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    JSONObject obj = new JSONObject();
                    obj.put("name", list.get(i).get("department_name").toString());
                    obj.put("departmentCode", list.get(i).get("department_code").toString());//转入科室编码
                    //int num=patientService.getEnterAndExitDepartment(map);
                    //直接通过sql查出数据
                    obj.put("value", list.get(i).get("department_count").toString());
                    //obj.put("value",num);
                    array.add(obj);
                }
            }*/
            json.put("data", list);
            json.put("msg", "查询成功");
            json.put("code", HttpCode.OK_CODE.getCode());
        } catch (Exception e) {
            System.out.println("getEnterDepartment:" + e);
        }
        return json.toString();
    }

    /**
     * 统计分析--出入科--转出科室分析
     *
     * @return
     */
    @RequestMapping(value = "/getExitDepartment", method = RequestMethod.POST)
    @ResponseBody
    public String getExitDepartment(@RequestBody(required = false) Map<String, Object> map, HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");

        User user=(User)session.getAttribute("user");
        if(user!=null && StringUtils.isNotEmpty(user.getTenantId())){
            String tenantId = user.getTenantId();
            if(TenantEnum.ICU.getTenantId().equals(tenantId)){
                map.put("status",TenantEnum.ICU.getPatientStatus());
                map.put("department",TenantEnum.ICU.getDepartmentName());
            } else if (TenantEnum.SHENNEI.getTenantId().equals(tenantId)) {
                map.put("status",TenantEnum.SHENNEI.getPatientStatus());
                map.put("department",TenantEnum.SHENNEI.getDepartmentName());
            }
        }

        if (map.get("type").toString().equals("按天")) {
            String startTime = map.get("startTime").toString();
            String endTime = map.get("endTime").toString();
            map.put("exitStartTime", startTime);
            map.put("exitEndTime", endTime);
            map.put("flag", 0);// 出科
        }
        if (map.get("type").toString().equals("按月")) {
            String year = "";
            if (map.get("year") == null || "".equals(map.get("year"))) {
                Calendar date = Calendar.getInstance();
                year = String.valueOf(date.get(Calendar.YEAR));
            }
            String startTime = year + "-01-01";
            String endTime = year + "-12-31";
            map.put("exitStartTime", startTime);
            map.put("exitEndTime", endTime);
            map.put("flag", 0);// 出科
        }

        List<Map<String, Object>> list = patientMiddleService.getAllExitDepartment(map);
        /*List<Map<String, Object>> list = patientService.getAllExitDepartment(map);
        JSONArray array = new JSONArray();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                JSONObject obj = new JSONObject();
                obj.put("name", list.get(i).get("department_name").toString());
                obj.put("toDepartmentCode", list.get(i).get("to_department_code").toString());//转出科室编码
                //int num=patientService.getEnterAndExitDepartment(map);
                //obj.put("value",num);
                //直接通过sql查出数据
                obj.put("value", list.get(i).get("department_count").toString());
                array.add(obj);
            }
        }*/
        json.put("data", list);
        json.put("msg", "查询成功");
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 统计分析--出入科--趋势分析
     *
     * @return
     */
    @RequestMapping(value = "/getNumByExitType", method = RequestMethod.POST)
    @ResponseBody
    public String getNumByExitType(@RequestBody(required = false) Map<String, Object> map, HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");

        User user=(User)session.getAttribute("user");
        if(user!=null && StringUtils.isNotEmpty(user.getTenantId())){
            String tenantId = user.getTenantId();
            if(TenantEnum.ICU.getTenantId().equals(tenantId)){
                map.put("status",TenantEnum.ICU.getPatientStatus());
            } else if (TenantEnum.SHENNEI.getTenantId().equals(tenantId)) {
                map.put("status",TenantEnum.SHENNEI.getPatientStatus());
            }
        }

        try {
            Map<String, Object> map1 = patientService.getExitpatientNum(map);
            json.put("data", map1);
            json.put("msg", "查询成功");
            json.put("code", HttpCode.OK_CODE.getCode());
        } catch (Exception e) {
            System.out.println("getNumByExitType:" + e);
        }
        return json.toString();
    }

    /**
     * 模拟查询视图
     *
     * @return
     */
    @RequestMapping(value = "/queryListTest", method = RequestMethod.POST)
    @ResponseBody
    public String queryListTest(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        List<Map<String, Object>> list = patientService.queryListTest(map);
        System.out.println("------模拟查询视图-------开始---------");
        if (list != null && list.size() > 0) {
            System.out.println("list:" + list.toString());
            json.put("data", JSONArray.fromObject(list));
            json.put("code", HttpCode.OK_CODE.getCode());
            json.put("msg", "查询成功");
        }
        System.out.println("------模拟查询视图-------结束--------");
        return json.toString();
    }

    /**
     * 病人管理--首页--查询病人监护仪及采集频率
     *
     * @return
     */
    @RequestMapping(value = "/queryPatientMonitor", method = RequestMethod.POST)
    @ResponseBody
    public String queryPatientMonitor(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        Map<String, Object> m = patientService.queryPatientMonitor(map);
        if (m != null) {
            m.put("frequency", "60min/次");//默认频率60min/次
            List<CommonSetting> commonSetting = commonSettingService.getCommonSettingByType(map);
            if (!CollectionUtils.isEmpty(commonSetting) && StringUtils.isNotEmpty(commonSetting.get(0).getSettingContent())) {
                m.put("frequency", commonSetting.get(0).getSettingContent());
            }
            json.put("data", JSONObject.fromObject(m));
            json.put("code", HttpCode.OK_CODE.getCode());
            json.put("msg", "查询成功");
        }
        return json.toString();
    }

    @ApiOperation("根据条件查询患者信息")
    @RequestMapping(value = "/getPatientByConditions", method = RequestMethod.POST)
    @ResponseBody
    public Patient getPatientByConditions(@RequestBody Map<String, Object> map) {
        map.put("status", "-1");
        return patientService.getPatientByConditions(map);
    }

    @ApiOperation("启用或关闭脉搏记录")
    @RequestMapping(value = "/openPulseRecord", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult openPulseRecord(@RequestBody Map<String, Object> map) {
        return patientService.openPulseRecord(map);
    }

    @ApiOperation("获取查询360系统url")
    @RequestMapping(value = "/getUrl", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult get360ViewUrl(@RequestBody Map<String, Object> map) {
        return patientService.get360ViewUrl(map);
    }

    /**
     * 更新病人入科时间
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/updateEnterTime", method = RequestMethod.POST)
    @ResponseBody
    public String updateEnterTime(@RequestBody(required = false) Map<String, Object> map) throws ParseException {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "系统开小差了，请稍后再试。");
        if (map != null && map.containsKey("id") && map.containsKey("enterTime")) {
            if (map.get("enterTime") == null || "".equals(map.get("enterTime"))) {
                json.put("msg", "参数错误");
            }
            Patient patient = patientService.queryData(map.get("id").toString());
            if (patient != null) {
                Date enterTime = DateUtil.yyyyMMddHHmmssSdfToDate(map.get("enterTime").toString());
                patient.setEnterTime(enterTime);
                patientService.update(patient);
                json.put("msg", "更新成功");
            } else {
                json.put("msg", "更新失败，没有这个对象。");
                return json.toString();
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 更新病人的年龄
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/updateAge", method = RequestMethod.POST)
    @ResponseBody
    public String updateAge(@RequestBody(required = false) Map<String, Object> map) throws ParseException {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "系统开小差了，请稍后再试。");
        if (map != null && map.containsKey("id") && map.containsKey("age")) {
            if (map.get("age") == null || "".equals(map.get("age"))) {
                json.put("msg", "参数错误");
            }
            Patient patient = patientService.queryData(map.get("id").toString());
            if (patient != null) {
                patient.setAge(map.get("age").toString());
                patientService.update(patient);
                json.put("data", patient);
                json.put("msg", "更新成功");
            } else {
                json.put("msg", "更新失败，没有这个对象。");
                return json.toString();
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 更新患者的床位信息
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/updateBedCode", method = RequestMethod.POST)
    @ResponseBody
    public String updateBedCode(@RequestBody(required = false) Map<String, Object> map, HttpSession session) throws ParseException {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "系统开小差了，请稍后再试。");
        if (map != null && map.containsKey("id") && map.containsKey("bedCode")) {
            if (map.get("bedCode") == null || "".equals(map.get("bedCode"))) {
                json.put("msg", "参数错误");
            }
            Patient patient = patientService.queryData(map.get("id").toString());
            if (patient != null) {
                patient.setBedCode(map.get("bedCode").toString());
                patientService.update(patient);

                savePatientTransferInfo(map.get("bedCode").toString(), patient,PatientEvent.TRANFER_BED.getCode(),(User)session.getAttribute("user"));
                json.put("data", patient);
                json.put("msg", "更新成功");
            } else {
                json.put("msg", "更新失败，没有这个对象。");
                return json.toString();
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    private void savePatientTransferInfo(String name, Patient patient,String type,User user) {
        PatientTransferInfo transferInfo = new PatientTransferInfo();
        transferInfo.setId(getUUID());
        transferInfo.setPatientId(patient.getId());
        transferInfo.setVisitCode(patient.getVisitCode());
        transferInfo.setVisitId(patient.getVisitId());
        transferInfo.setDataSource(1);
        transferInfo.setCreateTime(LocalDateTime.now());
        transferInfo.setDataTime(LocalDateTime.now());
        if(StringUtils.isNotEmpty(name)){
            transferInfo.setName(name);
        }
        transferInfo.setType(type);
        transferInfo.setUserId(user.getId());
        patientTransferInfoService.save(transferInfo);
    }

    /**
     * 查询空床位列表
     *
     * @return
     */
    @RequestMapping(value = "/getBedNullPatientList", method = RequestMethod.POST)
    @ResponseBody
    public String getBedNullPatientList(HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");

        User user=(User)session.getAttribute("user");
        if(user==null || org.apache.commons.lang3.StringUtils.isEmpty(user.getTenantId())){
            json.put("msg", "科室信息为空");
            return json.toString();
        }
        Map<String,Object> map = new HashMap<>();

        String tenantId = user.getTenantId();
        if(TenantEnum.ICU.getTenantId().equals(tenantId)){
            map.put("officeCode",TenantEnum.ICU.getOfficeCode());
            map.put("status",TenantEnum.ICU.getPatientStatus());
        } else if (TenantEnum.SHENNEI.getTenantId().equals(tenantId)) {
            map.put("status",TenantEnum.SHENNEI.getPatientStatus());
            map.put("officeCode",TenantEnum.SHENNEI.getOfficeCode());
        }

        List<Map<String, Object>> list = patientService.getBedNullPatientList(map);
        if (list != null && list.size() > 0) {
            json.put("data", JSONArray.fromObject(list));
            json.put("msg", "查询成功");
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    @ApiOperation("测试监护仪ip是否通畅")
    @RequestMapping(value = "/testIp", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult testMonitorIp(@RequestBody(required = false) Map<String, Object> map,HttpSession session) {
        User user=(User)session.getAttribute("user");
        if (map == null) map = new HashMap<>();
        if(user!=null && StringUtils.isNotEmpty(user.getTenantId())){
            String tenantId = user.getTenantId();
            map.put("tenantId",tenantId);
        }

        return patientService.testMonitorIp(map);
    }

    @ApiOperation("新增或者修改患者个人新旧表单变量标识")
    @RequestMapping(value = "/updateFormSign", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult updateSyncNewOrOldVitalSign(@RequestBody Map<String, Object> map) {
        return patientService.updateSyncNewOrOldVitalSign(map);
    }

    @ApiOperation("批量修改患者个人新旧表单变量标识")
    @RequestMapping(value = "/updateFormSignList", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult batchUpdateSyncNewOrOldVitalSign(@RequestBody Map<String, Object> map) {
        return patientService.batchUpdateSyncNewOrOldVitalSign(map);
    }

    @ApiOperation("更新已出科患者床位")
    @RequestMapping(value = "/updateExitBed",method= RequestMethod.POST)
    @ResponseBody
    public HttpResult updateExitBed(@RequestBody Map<String,Object> map){
        return patientService.updateExitBed(map);
    }


    @ApiOperation("更新患者状态")
    @RequestMapping(value = "/updateFlag",method= RequestMethod.POST)
    @ResponseBody
    public HttpResult updateFlag(@RequestBody Map<String,Object> map,HttpSession session){
        User user=(User)session.getAttribute("user");
        if(user!=null && StringUtils.isNotEmpty(user.getTenantId())){
            String tenantId = user.getTenantId();
            if(TenantEnum.ICU.getTenantId().equals(tenantId)){
                map.put("status",TenantEnum.ICU.getPatientStatus());
            } else if (TenantEnum.SHENNEI.getTenantId().equals(tenantId)) {
                map.put("status",TenantEnum.SHENNEI.getPatientStatus());
            }
        }
        return patientService.updateFlag(map);
    }
}
